package com.yueqianshop.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.yueqianshop.common.exception.NoStockException;
import com.yueqianshop.common.to.OrderTo;
import com.yueqianshop.common.to.SkuHasStockVo;
import com.yueqianshop.common.to.StockDetailTo;
import com.yueqianshop.common.to.StockLockedTo;
import com.yueqianshop.common.utils.R;
import com.yueqianshop.ware.Vo.LockStockResult;
import com.yueqianshop.ware.Vo.OrderItemVo;
import com.yueqianshop.ware.Vo.OrderVo;
import com.yueqianshop.ware.Vo.WareSkuLockVo;
import com.yueqianshop.ware.entity.WareOrderTaskDetailEntity;
import com.yueqianshop.ware.entity.WareOrderTaskEntity;
import com.yueqianshop.ware.feign.OrderFeignService;
import com.yueqianshop.ware.feign.ProductFeignService;
import com.yueqianshop.ware.service.WareOrderTaskDetailService;
import com.yueqianshop.ware.service.WareOrderTaskService;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yueqianshop.common.utils.PageUtils;
import com.yueqianshop.common.utils.Query;

import com.yueqianshop.ware.dao.WareSkuDao;
import com.yueqianshop.ware.entity.WareSkuEntity;
import com.yueqianshop.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    OrderFeignService orderFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if(!StringUtils.isEmpty(skuId)){
            queryWrapper.eq("sku_id",skuId);
        }
        String wareId = (String) params.get("wareId");
        if(!StringUtils.isEmpty(wareId)){
            queryWrapper.eq("ware_id",wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo vo = new SkuHasStockVo();
            //查询当前sku的总库存量
            Long count = baseMapper.getSkuStock(skuId);
            vo.setSkuId(skuId);
            vo.setHasStock(count == null ? false : count > 0);
            return vo;
        }).collect(Collectors.toList());
        return collect;
        
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
       List<WareSkuEntity> entities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
       if(entities.size() == 0 || entities == null){
           WareSkuEntity skuEntity = new WareSkuEntity();
           skuEntity.setSkuId(skuId);
           skuEntity.setStock(skuNum);
           skuEntity.setWareId(wareId);

           try{
               R info = productFeignService.info(skuId);
               Map<String,Object> data = (Map<String,Object>)info.get("skuinfo");
               skuEntity.setSkuName((String) data.get("skuname"));

           }catch (Exception e){

           }


           wareSkuDao.insert(skuEntity);

       }else {
           wareSkuDao.addStock(skuId,wareId,skuNum);
       }

    }

    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVo vo) {
        //0、保存库存工作单，方便追溯库存锁定情况
        WareOrderTaskEntity taskEntity = new WareOrderTaskEntity();
        taskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(taskEntity);


        // 1、按照下单的收货地址，找到一个就近仓库，锁定库存

        // 1、找到每个商品在哪个仓库都有库存
        List<OrderItemVo> locks = vo.getLocks();
        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            stock.setSkuId(skuId);
            stock.setNum(item.getCount());
            //查询这个商品在哪个仓库有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            stock.setWareId(wareIds);
            return stock;
        }).collect(Collectors.toList());

        // 2、锁定库存 为每个商品锁定库存
        for (SkuWareHasStock hasStock : collect) {
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds == null || wareIds.size() == 0){
                //没有任何库存有这个商品的库存
                throw new NoStockException(skuId);
            }
            for (Long wareId : wareIds) {
                //成功返回1；否则就是0
                Long count = wareSkuDao.lockSkuStock(skuId,wareId,hasStock.getNum());
                if (count == 1){//根据返回影响行 判断  为1 代表库存锁定成功
                    skuStocked = true;

                    //TODO  告诉MQ 库存锁定成功
                    WareOrderTaskDetailEntity taskDetailEntity = new WareOrderTaskDetailEntity(null, skuId, "", hasStock.getNum(), taskEntity.getId(), wareId, 1);
                    wareOrderTaskDetailService.save(taskDetailEntity);
                    StockLockedTo stockLockedTo = new StockLockedTo();
                    stockLockedTo.setTaskId(taskEntity.getId());
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(taskDetailEntity, stockDetailTo);
                    stockLockedTo.setTaskDetail(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockedTo);


                    break;
                    //当仓库锁失败，重试下一个仓库
                }
            }
            if (skuStocked == false){
                //当前商品所有仓库都没有锁住
                throw new NoStockException(skuId);
            }
        }
        // 3、肯定全部都是锁定成功的
        return true;
    }

    @Override
    public void unlock(StockLockedTo stockLockedTo) {
        StockDetailTo detailTo = stockLockedTo.getTaskDetail();
        WareOrderTaskDetailEntity detaiEntity = wareOrderTaskDetailService.getById(detailTo.getId());
        if(detaiEntity != null){
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(stockLockedTo.getTaskId());
            R r = orderFeignService.getOrderByOrderSn(taskEntity.getOrderSn());
            if (r.getCode() == 0){
                OrderVo order = r.getData("order", new TypeReference<OrderVo>() {
                });
                //没有这个订单||订单状态已取消  解锁库存
                if(order == null || order.getStatus() == 4){
                    //为保证幂等性，只有当工作单处于被锁定的情况下才进行解锁
                    if(detaiEntity.getLockStatus() == 1){
                        //当前库存工作单详情  状态 1   已锁定但未解锁可以被解锁
                        unLockStock(detailTo.getSkuId(), detailTo.getWareId(), detailTo.getSkuNum(), detailTo.getTaskId());
                    }
                }
            }else {
                //消息拒绝以后重新放到队列中，让别人继续消费解锁
                throw new RuntimeException("远程调用失败");
            }
        }else{

        }
    }

    /**
     * 取消订单，解锁库存
     * 防止因订单服务卡顿，导致订单状态消息一直改不了，库存消息优先于订单消息过期，
     * 当前卡顿的订单永远得不到库存的解锁
     * @param orderTo
     */
    @Transactional
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        WareOrderTaskEntity orderTask = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        List<WareOrderTaskDetailEntity> taskDetail = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", orderTask.getId()).eq("lock_status", 1));
        for (WareOrderTaskDetailEntity taskDetailEntity : taskDetail) {
            unLockStock(taskDetailEntity.getSkuId(), taskDetailEntity.getWareId(), taskDetailEntity.getSkuNum(), taskDetailEntity.getId());
        }
    }


    private void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetaiId){
        baseMapper.unLockStock(skuId, wareId, num);
        // 更新库存工作单状态
        WareOrderTaskDetailEntity taskDetail = new WareOrderTaskDetailEntity();
        taskDetail.setId(taskDetaiId);
        taskDetail.setLockStatus(2);
        wareOrderTaskDetailService.updateById(taskDetail);
    }



    @Data
    class SkuWareHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }


}